<template>
  <div :style="'width: 100%; max-width: ' + props.width + 'px;height: ' + props.height + 'px'">
    <span v-if="inputDisabled || props.showText" class="image-box">
      <el-image
        v-if="imageUrl !== ''"
        preview-teleported
        hide-on-click-modal
        :src="imageUrl"
        :preview-src-list="[imageUrl]"
        style="width:100%;height:100%"
        fit="scale-down"
      />
    </span>
    <span v-else-if="!inputDisabled" class="image-edit-box">
      <el-upload :class="['ac-image', {'is-disabled': inputDisabled}]" action=""
        :disabled="inputDisabled"
        :http-request = "handleUpload"
        :show-file-list="false"
        :accept="'image/*'"
        :before-upload="handleBeforeUpload"
      >
        <ac-icon v-if="loading" size="30" color="#999" iconId="018dcab3d3dfd6e82393" class="spinner" />
        <span v-else-if="imageUrl && !loading" class="image-item">
          <ac-icon size="14" color="red" iconId="018dc9c3efd3a0502886" title="删除" @click.stop="deleteImage" />
          <img :src="imageUrl" alt />
        </span>
        <ac-icon v-else size="30" color="#999" iconId="018dca3b4707c4c43a2f"></ac-icon>
      </el-upload>
    </span>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'
import { ElMessage, useDisabled, useFormItem } from "element-plus";
import api from "@/http/api";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: [Number, String],
  width: {
    type: Number,
    default: 100
  },
  height: {
    type: Number,
    default: 100
  },
  showText: Boolean
});

const loading = ref(false);
const fileId = ref('');
const imageUrl = ref('');
const inputDisabled = useDisabled();
const formItem = useFormItem();

const handleUpload = (data) => {
  return new Promise((resolve, reject) => {
    api.upload({'file': data.file, builtin: '1', type: data.file.type}).then((res) => {
      loading.value = false;
      fileId.value = res.data.id;
      imageUrl.value = URL.createObjectURL(data.file);
      emit('update:modelValue', res.data.id);
      nextTick(() => {
        if (formItem && formItem.formItem) {
          formItem.formItem.validate('change');
        }
      });
      resolve();
    }).catch(() => {
      loading.value = false;
      reject();
    });
  });
};

const handleBeforeUpload = (file) => {
  if (loading.value) {
    ElMessage.error("图片正在上传中，请稍候再试！");
    return false;
  }
  loading.value = true;

  const isImage = file.type.includes("image");
  if (!isImage) {
    loading.value = false;
    ElMessage.error("上传文件类型必须是图片!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    loading.value = false;
    ElMessage.error("上传图片大小不能超过 2MB!");
  }
  return isImage && isLt2M;
};

const deleteImage = () => {
  fileId.value = '';
  imageUrl.value = '';
  emit('update:modelValue', '');
  nextTick(() => {
    if (formItem && formItem.formItem) {
      formItem.formItem.validate('change');
    }
  });
};

const loadData = () => {
  if ((props.modelValue || '') !== '') {
    fileId.value = props.modelValue;
    imageUrl.value = import.meta.env.VITE_IMAGE_PATH + fileId.value;
  } else {
    fileId.value = '';
    imageUrl.value = '';
  }
};

watch(() => props.modelValue, (newVal) => {
  fileId.value = '';
  imageUrl.value = '';

  if ((newVal || '') === '' || (fileId.value || '') === '' || newVal !== fileId.value) {
    loadData();
  }
});

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.ac-image {
  height: 100%;
  width: 100%;
  flex: 1;
  justify-content: center;
  align-items: center;
  display: flex;
  border: 1px dashed #c2c2c2;
}
.ac-image :deep(.el-upload) {
  display: flex;
  text-align: center;
  cursor: pointer;
  outline: 0;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.ac-image :deep(.el-upload span) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.ac-image:not(.is-disabled) :deep(.el-upload) {
  cursor: pointer;
}
.ac-image:not(.is-disabled) :deep(.el-upload:hover) {
  border-color: #409EFF;
}
.loading-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
}
.plus-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
}
.ac-image img {
  max-width: 100%;
  max-height: 100%;
}
.image-box {
  border: 1px dashed #d9d9d9;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  box-sizing: border-box;
}
.image-box img {
  max-width: 100%;
  max-height: 100%;
}
.ac-image :deep(.el-upload:after) {
  display: block;
  margin-top: 100%;
  content: ""
}
.image-item {
  position: relative;
}
.image-item .ac-icon {
  position: absolute;
  top: 5px;
  right: 5px;
}
</style>